<?php

//for easy install migrations mysql
function installMysqlPart($enable) {
  $db = getenv('EV_php_name');
  $pass = getenv('EV_php_pass');
  //scale all backends hiden mysql scripts
  $remove_php_open_key_tmp = 'sed "s/<?php//g" -i $1';
  $remove_php_open_multiline_comment_tmp = 'sed "s/\/\*//g" -i $1';
  $remove_php_close_multiline_comment_tmp = 'sed "s/\*\///g" -i $1';
  $remove_php_close_key_tmp = 'sed "s/?>//g" -i $1';
  $remove_first_space_tmp = 'sed "1{/^$/d}" -i $1';
  $remove_second_space_tmp = 'sed "1{/^$/d}" -i $1';
  $remove_last_space_tmp = 'sed -z "s/.$//" -i $1';

  $add_php_multiline_comment = 'sed "1s/^/\/\*\n/" -i $1';
  $add_php_open_key_comment = 'sed "1s/^/<?php\n/" -i $1';
  $add_php_close_multiline_comment = 'echo "*/" >> $1';
  $add_php_close_key = 'echo "?>" >> $1';
  $add_last_space = 'sed -z "s/.$//" -i $1';

  $cmd = <<<CMD
  #!/bin/bash

  unblockSqlBackenduery() {
      if [ -f \$1 ]
      then
          $remove_php_open_key_tmp
          $remove_php_open_multiline_comment_tmp
          $remove_php_close_multiline_comment_tmp
          $remove_php_close_key_tmp
          $remove_first_space_tmp
          $remove_second_space_tmp
          $remove_last_space_tmp
      fi
  }

  runBackendnServe() {
      if [ -f \$1 ]
      then
          mysql -uroot -p$pass $db < \$1
      fi
  }

  blockSqlBackenduery() {
      if [ -f \$1 ]
      then
          $add_php_multiline_comment
          $add_php_open_key_comment
          $add_php_close_multiline_comment
          $add_php_close_key
          $add_last_space
      fi
  }

  runSteps() {
      unblockSqlBackenduery \$1
      runBackendnServe \$1 || true
      blockSqlBackenduery \$1
  }

  scaleBackend() {
      for backendSql in backend/*/*.sql.php; do runSteps \$backendSql; done
  }

  scaleBackend 2>&1
  CMD;

  if ($enable) {
    echo '<h3>Database information: </h3>';
    echo '<br>';
    echo exec($cmd);
  }

}

$enable = false;

echo $enable;

installMysqlPart($enable);

?>